package service

import (
	sqlc "bgs/db/sqlc"
	"bgs/util"
	"context"
)

// OpenDistributeStoreParam 开通分销门店参数
type OpenDistributeStoreParam struct {
	UserID        int64
	Name          string
	BrandID       int64
	Intro         string
	Pic           string
	DistributorID int64
}

// OpenDistributeStore 开通分销门店
func (s *StoreServiceImp) OpenDistributeStore(ctx context.Context, q *sqlc.Queries, ptr *OpenDistributeStoreParam) (storePtr *sqlc.Store, err error) {
	slog := util.NewContextLogger(ctx, s.slog)

	store, err := q.CreateBrandDistributeStore(ctx, sqlc.CreateBrandDistributeStoreParams{
		Origin:        string(sqlc.EmDataSourceLocal),
		Name:          ptr.Name,
		BrandID:       ptr.BrandID,
		Intro:         sqlc.NSFromString(ptr.Intro),
		Pic:           sqlc.NSFromString(ptr.Pic),
		DistributorID: sqlc.NInt64FromInt64(ptr.DistributorID),
	})
	if err != nil {
		return
	}
	slog.Info("1 创建分销门店 ok")

	storePtr = &store
	storeID := storePtr.ID

	_, err = s.EnsureStoreStatPtr(ctx, q, false, storeID)
	if err != nil {
		return
	}
	slog.Info("2 确保门店统计 ok")

	_, err = s.EnsureAccountInfo(ctx, q, false, storeID)
	if err != nil {
		return
	}
	slog.Info("2 确保门店账户信息 ok")

	return
}

// UpdateStoreInfoParam 更新门店信息
type UpdateStoreInfoParam struct {
	StoreID    int64
	Name       string
	Intro      string
	Pic        string
	HomepageBg string
	Tel        string
}

// OpenNew 开通新品牌
func (s *StoreServiceImp) UpdateStoreInfo(ctx context.Context, q *sqlc.Queries, ptr *UpdateStoreInfoParam) (storePtr *sqlc.Store, err error) {	
	store, err := q.UpdateStoreInfo(ctx, sqlc.UpdateStoreInfoParams{
		ID:         ptr.StoreID,
		Name:       ptr.Name,
		Intro:      sqlc.NSFromString(ptr.Intro),
		Pic:        sqlc.NSFromString(ptr.Pic),
		HomepageBg: sqlc.NSFromString(ptr.HomepageBg),
		Tel:        sqlc.NSFromString(ptr.Tel),
	})
	if err != nil {
		return
	}
	storePtr = &store
	s.ClearCache(storePtr.ID)
	return
}
